<template>
  <div v-loading="isloading" class="fenleicontainer">
    <div>
      <div class="selectHeader">
        <div class="select-wrapper">
          <div class="selectBox">
            <div class="selectTitle">
              <i class="iconfont icon-sousuo" />按条件查询
            </div>

            <div style="margin-top: 10px">
              <el-input
                v-model="listquery.town"
                style="width: 200px"
                placeholder="乡镇名称"
                clearable
              ></el-input>

              <el-select
                v-model="listquery.isAuthorized"
                clearable
                placeholder="是否关联编制单位"
                style="width: 200px"
              >
                <el-option
                  v-for="(item, index) in listUnit"
                  :label="item.name"
                  :value="item.value"
                  :key="index"
                >
                </el-option>
              </el-select>
              <el-button type="success" icon="el-icon-search" @click="search"
                >搜索</el-button
              >
              <el-button
                type="warning"
                icon="el-icon-refresh-left"
                @click="reset"
                >重置</el-button
              >
            </div>

            <div style="margin-top: 10px">
              <span style="color: #4778c7">规划编制类型:</span>
              <el-radio-group
                size="small"
                v-model="listquery.planType"
                @change="valueChange"
              >
                <el-radio-button border label="">全部</el-radio-button>
                <el-radio-button
                  border
                  v-for="(item, index) in options2"
                  :key="index"
                  :label="item"
                  >{{ item }}</el-radio-button
                >
              </el-radio-group>
            </div>
            <div class="row-area" style="margin-top: 10px">
              <span style="color: #4778c7">行政区域选择：</span>
              <el-select
                placeholder="所属市选择"
                v-model="currentLiindex"
                @change="cityChange"
                v-if="iscityshow"
                clearable
                @clear="cityclear"
              >
                <el-option
                  v-for="(item, index) in citylist"
                  :key="item.id"
                  :label="item.label"
                  :value="index"
                />
              </el-select>
              <ul class="countryArea" v-if="areaShow">
                <li
                  v-for="(item, i) in cityChildren"
                  :key="i"
                  @click="liChange(i)"
                  :class="{ areaActive: i == currentareaindex }"
                >
                  {{ item.label }}
                </li>
              </ul>
              <!-- <el-select
                placeholder="乡镇选择"
                v-model="town"
                @change="townChange"
                v-if="istownshow"
                clearable
              >
                <el-option
                  v-for="item in townlist"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select> -->
            </div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <!-- <div class="editWrap" v-if="isShow2"></div> -->

      <div class="headerbutton">
        <div class="header"><i class="el-icon-d-arrow-right"></i>乡镇列表</div>
        <div class="link-btn-group">
          <!-- <el-button
            type="warning"
            icon="el-icon-link"
            @click="downloadclassifyExcel"
            style="margin-right: 5px"
            >导出</el-button
          > -->
          <el-upload
            class="upload-demo"
            action=""
            :http-request="unitLinkmore"
            :show-file-list="false"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          >
            <el-button type="primary" icon="el-icon-link">批量关联</el-button>
          </el-upload>
          <el-button
            type="success"
            icon="el-icon-download"
            @click="downloadExcel"
            >下载批量关联模板</el-button
          >
        </div>
      </div>
      <!-- :tableData="result.slice((curPage - 1) * pageSize, curPage * pageSize)" -->
      <el-table
        :data="tableData"
        :span-method="objectSpanMethod"
        border
        row-key="id"
        style="width: 100%"
        class="eltable"
        :default-expand-all="isExpand"
        @expand-change="expand"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="序号" width="100" prop="id">
          <template slot-scope="{ $index }">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="town" label="乡镇名" width="120" />
        <el-table-column label="所属行政区划" width="300">
          　<template slot-scope="scope">
            <span>{{ scope.row.city }}-{{ scope.row.country }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="planType" label="规划编制分类" width="150" />

        <el-table-column prop="nickName" label="所属编制单位(联系人+电话)">
          　<template slot-scope="scope">
            <div v-if="scope.row.profileData.length > 0">
              <p
                style="margin: 2px 0"
                v-for="v in scope.row.profileData"
                :key="v.profileName"
              >
                {{ v.profileName }}(联系人:{{ v.contactName }} 电话:{{
                  v.contactPhone
                }})
              </p>
            </div>
            <span v-else>暂未关联</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="350" fixed="right">
          　<template slot-scope="scope">
            <el-button
              type="success"
              icon="el-icon-link"
              size="mini"
              v-if="scope.row.profileData.length <= 0"
              @click="open(scope.row)"
              >关联</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              v-else
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-popconfirm
              title="删除将会清除所有关联关系"
              icon="el-icon-info"
              v-if="scope.row.profileData.length > 0"
              icon-color="red"
              @confirm="handleDelete(scope.row.id)"
            >
              <el-button
                type="danger"
                slot="reference"
                icon="el-icon-delete"
                size="mini"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="tableData.length > 0"
        class="elpagi"
        :total="total"
        @size-change="getdata"
        @current-change="getdata"
        @prev-click="getdata"
        @next-click="getdata"
        :current-page.sync="listquery.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size.sync="listquery.pageSize"
        layout="total,sizes, prev, pager, next, jumper"
      />
    </div>
    <el-dialog
      :title="dialogStatus == 'add' ? ' 关联编制单位' : '编制单位关联修改'"
      :visible.sync="isDialogShow"
      width="600px"
      :append-to-body="true"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        label-position="left"
      >
        <el-form-item label="所属编制单位:" prop="nickName">
          <el-select
            v-model="form.nickName"
            placeholder="请选择"
            value-key="value"
            size="mini"
            multiple
            filterable
            class="select2"
            style="width: 400px"
            @change="unitChange"
            :multiple-limit="3"
          >
            <el-option
              v-for="(item, index) in unittype"
              :key="item.name"
              :label="item.name"
              :value="index"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div v-for="(item, index) in contactList" :key="index">
          <el-form-item label="联系人:" required>
            <el-input
              type="text"
              :rows="8"
              :placeholder="unittype[form.nickName[index]].name"
              size="mini"
              clearable
              v-model="contactList[index].contactName"
              style="width: 385px"
            />
          </el-form-item>
          <el-form-item label="联系电话" required>
            <el-input
              type="text"
              :rows="8"
              :placeholder="unittype[form.nickName[index]].name"
              size="mini"
              clearable
              v-model="contactList[index].contactPhone"
              style="width: 385px"
            >
            </el-input>
          </el-form-item>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogShow = false">取 消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'add' ? submitForm('form') : editData()"
          >提交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { profilelistSimple } from "@/api/index.js";
import XLSX from "xlsx";
// import { mapGetters } from "vuex";
import { townList, settownlink, deltownlink } from "@/api/town.js";

import { picHost } from "@/settings.js";
import queryMixin from "@/mixins/countquery1.js";
export default {
  data() {
    return {
      listquery: {
        pageSize: 10,
        currentPage: 1,
        completionYear: "",
        isAuthorized: "",
        key: "",
        isMerge: false,
        town: "",
      },
      listUnit: [
        { name: "暂未关联", value: false },
        { name: "已关联", value: true },
      ],
      fileList: [],
      fileDataList: [],
      total: 0,
      AAA: {},
      filterShow: true,
      valueData: "",
      isloading: false,
      name: "村庄分类表",
      isShow2: false,
      form1: {},
      form: {
        nickName: [],
        contactList: [],
      },
      contactList: [],
      unittype: [],
      dialogStatus: "",
      rules: {
        nickName: [
          { required: true, message: "请选择所属编制单位", trigger: "blur" },
        ],
        contactName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        contactPhone: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
        ],
      },
      formobj: {
        city: "",
        completionYear: "",
        country: "",
        id: "",
        planType: "",
        town: "",
      },
      options2: ["单独编制", "总规统筹", "合并编制"],
      isExpand: false,

      tableData: [],
      isDialogShow: false,
      townId: null,
      role: "",
      scopeData: null,
    };
  },

  mixins: [queryMixin],

  mounted() {
    this.AAA = new Map();
    this.getunittype();
    this.role = this.$store.getters.user.roles[0].name;
    this.getdata();
    this.AAA = new Map();
  },
  methods: {
    search() {
      this.listquery.currentPage = 1;
      this.listquery.pageSize = 10;
      this.getdata();
    },
    reset() {
      this.listquery = {
        pageSize: 10,
        currentPage: 1,
        planType: "",
        key: "",
        isMerge: false,
      };
    },
    expand(data, row) {
      data.state = row;
      this.AAA.set(data.id, row);
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex > 2) {
        if (row.children && row.state) {
          return {
            rowspan: row.children.length + 1,
            colspan: 1,
          };
        } else if (row.isChildren) {
          return {
            rowspan: 1,
            colspan: 0,
          };
        } else {
          return {
            rowspan: 1,
            colspan: 1,
          };
        }
      }
    },

    async getunittype() {
      let data = {
        pageSize: 500,
        currentPage: 1,
      };
      let res = await profilelistSimple(data);
      // this.unittype = res.data.content
      this.unittype = [];
      res.data.content.forEach((element) => {
        this.unittype.push({
          name: element.name,
          id: element.id,
        });
      });
    },

    //新增关联窗口
    open(row) {
      this.form = {
        nickName: "",
        contactName: "",
        contactPhone: "",
      };
      this.townId = row.id;
      this.contactList = [];
      this.dialogStatus = "add";
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
      this.isDialogShow = true;
    },
    //新增提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let list = this.contactList;
          settownlink(list)
            .then((v) => {
              this.getdata();
              this.$notify({
                title: "成功",
                message: "添加成功",
                type: "success",
              });
              this.isDialogShow = false;
            })
            .catch((e) => {
              this.$notify.error({
                title: "错误",
                message: e.response.data.message,
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //打开修改关联关系的弹出窗
    handleUpdate(row) {
      this.townId = row.id;
      this.form.nickName = [];
      this.unittype.map((v, i) => {
        if (row.profileNames.indexOf(v.name) > -1) {
          this.form.nickName.push(i);
        }
      });
      this.contactList = row.profileData.map((v) => {
        return {
          id: v.id,
          profileId: v.profileId,
          townId: v.townId,
          contactName: v.contactName,
          contactPhone: v.contactPhone,
        };
      });
      this.dialogStatus = "edit";
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });

      this.scopeData = row;
      this.isDialogShow = true;
    },

    //提交修改关联关系
    editData() {
      this.$refs["form"].validate((valid) => {
        let list = this.contactList;
        if (valid) {
          settownlink(list)
            .then(() => {
              this.getdata();
              this.isDialogShow = false;
              this.$notify({
                title: "成功",
                message: "修改成功",
                type: "success",
                duration: 2000,
              });
            })
            .catch((e) => {
              this.$notify.error({
                title: "错误",
                message: e.response.data.message,
              });
            });
        }
      });
    },
    //清除关联关系
    handleDelete(id) {
      let params = new FormData();
      params.append("id", id);
      deltownlink(params)
        .then((v) => {
          this.getdata();
          this.$notify({
            title: "成功",
            message: "清除成功",
            type: "success",
          });
        })
        .catch((error) => {
          this.$notify.error({
            title: "错误",
            message: error.response.data.message,
          });
        });
    },
    //打开村庄分类弹出窗
    application(row) {
      this.formobj = Object.assign({}, row); // copy obj
      this.isShow2 = true;
      this.$nextTick(() => {
        this.$refs["formobj"].clearValidate();
      });
    },
    //关闭村庄分类弹出窗
    wrapclose() {
      this.isShow2 = false;
    },
    //村庄分类更新提交
    updateData() {
      this.$refs["formobj"].validate((valid) => {
        if (valid) {
          settownlink(this.formobj).then((v) => {
            this.isShow2 = false;
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
              duration: 2000,
            });
            this.getdata();
          });
        }
      });
    },
    //重置表单数据
    resetForm(formname) {
      this.formobj = {};
      this.$refs[formname].resetFields();
    },
    valueChange() {
      this.listquery.currentPage = 1;
      this.getdata();
    },
    //刷新乡镇列表
    async getdata() {
      this.isloading = true;
      if (this.valueData !== null) {
        this.listquery.startDate = this.valueData[0];
        this.listquery.endDate = this.valueData[1];
      } else {
        this.listquery.startDate = null;
        this.listquery.endDate = null;
      }
      let res = await townList(this.listquery);
      this.tableData = res.data.content;
      this.total = res.data.totalElements;
      this.tableData.forEach((element) => {
        if (element.children) {
          if (this.AAA.has(element.id)) {
            element.state = this.AAA.get(element.id);
          } else {
            element.state = this.isExpand;
          }
        }
      });
      this.AAA = new Map();

      this.isloading = false;
    },
    //上传批量关联
    unitLinkmore(data) {
      let file = data.file;
      let name = file.name;
      let fileType = name.split(".")[name.split(".").length - 1];
      if (fileType != "xls" && fileType != "xlsx") {
        this.$message.error("仅支持Excel文件");
        return;
      }
      this.isloading = true;
      var reader = new FileReader();
      reader.onload = (e) => {
        var data = e.target.result;
        var workbook = XLSX.read(data, { type: "binary" });
        if (workbook) {
          let worksheet1 = workbook.Sheets[workbook.SheetNames[0]];
          let sheet = XLSX.utils.sheet_to_json(worksheet1, { header: 1 });
          let sheetData = [];
          for (let i = 1; i < sheet.length; i++) {
            const element = sheet[i];
            if (!element[0] || element[0] == null || element[0].trim() == "") {
            } else {
              if (element.length < 4) {
                this.$message.error("表格不能存在空值");
              }
              sheetData.push({
                town: element[0].toString().trim(),
                profileName: element[1].toString().trim(),
                contactName: element[2].toString().trim(),
                contactPhone: element[3].toString().trim(),
              });
            }
          }
          settownlink(sheetData)
            .then((res) => {
              if (res.success) {
                this.$notify({
                  title: "成功",
                  message: "修改成功",
                  type: "success",
                  duration: 2000,
                });
                this.isloading = false;
                this.getdata();
              } else {
                this.$notify.error({
                  title: "关联失败",
                  message: res.message,
                });
                this.isloading = false;
              }
            })
            .catch((e) => {
              this.$message.error(e.response.data.message);
              this.isloading = false;
            });
        }
      };
      reader.readAsBinaryString(file);
    },

    //下载批量关联的模板
    downloadExcel() {
      window.open(picHost + "批量关联模板乡镇.xlsx");
    },

    unitChange() {
      let id = this.townId;
      let unittype = this.unittype;
      let list = [];

      this.form.nickName.forEach((v, i) => {
        if (this.dialogStatus === "add") {
          list.push({
            profileId: unittype[v].id,
            townId: id,
            contactName: "",
            contactPhone: "",
          });
        } else if (this.dialogStatus === "edit") {
          list.push({
            profileId: unittype[v].id,
            townId: id,
            contactName: "",
            contactPhone: "",
            profileName: "",
          });
          this.contactList.forEach((p, k) => {
            list.forEach((l) => {
              if (l.profileId == p.profileId) {
                l.contactName = p.contactName;
                l.contactPhone = p.contactPhone;
              }
            });
          });
        }
      });
      this.contactList = list;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../public/css/table.scss";
// @import "../../../../public/css/countheader.scss";

.fenleicontainer {
  margin: 5px;
  padding-bottom: 10px;
  overflow-y: auto;
  position: relative;
  height: 100%;
}
.icondiv {
  // background-color: #f2f2f2;
  border-top: 1px dashed #ccc;
  display: flex;
  cursor: pointer;
  justify-content: center;
  span {
    background-color: #f2f2f2;
    display: inline-block;
    padding: 5px 10px;
    margin: 0 auto;
    font-size: 12px;
    color: #4778c7;
  }
}
.headerbutton {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 20px;
  .header {
    line-height: 45px;
    margin-right: 5px;
    font-size: 15px;
    letter-spacing: 0.5px;
    font-weight: 600;
    color: #4778c7;
    i {
      color: #4778c7;
    }
  }
  .link-btn-group {
    display: flex;
    width: 340px;
    justify-content: space-between;
  }
}

.uploadbutton {
  display: flex;
  width: 100%;
  position: relative;
  background-color: #f2f2f2;
  padding-bottom: 5px;
  .upload-demo {
    display: flex;
    align-items: center;
    justify-content: right;
  }
}

.row-area {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.countryArea {
  height: 32px;
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-wrap: wrap;

  li {
    text-align: center;
    margin-right: 10px;
    font-weight: 400;
    font-size: 14px;
    line-height: 32px;
    cursor: pointer;
  }

  .active {
    border-bottom: 3px solid black;
  }
  .areaActive {
    background-color: #4cc8c7;
    color: #fff;
    border-radius: 5px;
    padding: 0 10px;
  }
}
.editWrap {
  background-color: rgb(0, 0, 0);
  opacity: 0.5;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
}
.editDiv {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 40%;
  height: 350px;
  background-color: #fff;
  transform: translate(-50%, -50%);
  z-index: 1001;
  .vi-name {
    line-height: 55px;
    font-size: 16px;
    padding-left: 20px;
    .blue {
      color: #4778c7;
    }
  }
  .elform {
    margin: 20px;
  }
  .tips {
    font-size: 12px;
    color: red;
    margin-top: -15px;
    margin-bottom: 15px;
  }
  .edit-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #ccc;
    span {
      font-size: 16px;
      font-weight: 500;
      color: #4778c7;
      i {
        margin-right: 5px;
      }
    }
    i {
      font-size: 18px;
      &:hover {
        color: #4778c7;
      }
    }
  }
}
</style>
